<template>
  <div class="video-player-container">
    <!-- 视频播放区域 -->
    <div class="video-container">
      <video
        v-if="src"
        ref="videoRef"
        class="video-element"
        @timeupdate="handleTimeUpdate"
        @loadedmetadata="handleMetadataLoaded"
        @ended="handleVideoEnded"
        @error="handleVideoError"
        @click="togglePlay"
        :style="{ width: width }"
      >
        <source :src="src" :type="type" />
        您的浏览器不支持视频播放
      </video>
      <img v-else :src="img" style="height: 100%" />
    </div>
    
    <!-- 控制栏 -->
    <div class="controls-container">
      <!-- 播放/暂停按钮 -->
      <div class="play-button" @click="togglePlay">
        <i class="control-icon" :class="isPlaying ? 'icon-pause' : 'icon-play'">
          <svg v-if="isPlaying" viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"></path>
          </svg>
          <svg v-else viewBox="0 0 24 24" width="24" height="24">
            <path fill="currentColor" d="M8 5v14l11-7z"></path>
          </svg>
        </i>
      </div>
      
      <!-- 当前时间 -->
      <div class="time-display current-time">{{ formatTime(currentTime) }}</div>
      
      <!-- 进度条 -->
      <div class="progress-bar-container" ref="progressBarRef" @click="handleProgressBarClick">
        <div class="progress-bar-background"></div>
        <div class="progress-bar-filled" :style="{ width: `${progressPercentage}%` }"></div>
        <div class="progress-bar-handle" :style="{ left: `${progressPercentage}%` }"
             @mousedown="startDrag"
             @touchstart="startDrag"></div>
      </div>
      
      <!-- 总时长 -->
      <div class="time-display total-time">{{ formatTime(duration) }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  img: {
    type: String,
    required: false
  },
  type: {
    type: String,
    default: 'video/mp4'
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  width: {
    type: String,
    default: '100%'
  }
});

// 视频元素引用
const videoRef = ref(null);
const progressBarRef = ref(null);

// 状态变量
const isPlaying = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const isDragging = ref(false);

// 计算进度百分比
const progressPercentage = computed(() => {
  if (duration.value === 0) return 0;
  return (currentTime.value / duration.value) * 100;
});

// 格式化时间为 mm:ss 格式
const formatTime = (timeInSeconds) => {
  if (isNaN(timeInSeconds) || timeInSeconds === Infinity) return '00:00';
  
  const minutes = Math.floor(timeInSeconds / 60);
  const seconds = Math.floor(timeInSeconds % 60);
  
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
};

// 切换播放/暂停
const togglePlay = () => {
  const video = videoRef.value;
  if (!video) return;
  
  if (video.paused || video.ended) {
    video.play();
    isPlaying.value = true;
  } else {
    video.pause();
    isPlaying.value = false;
  }
};

// 处理视频时间更新
const handleTimeUpdate = () => {
  if (isDragging.value) return;
  currentTime.value = videoRef.value?.currentTime || 0;
};

// 处理视频元数据加载完成
const handleMetadataLoaded = () => {
  duration.value = videoRef.value?.duration || 0;
  if (props.autoplay) {
    togglePlay();
  }
};

// 处理视频播放结束
const handleVideoEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
};

// 处理视频加载错误
const handleVideoError = () => {
  isPlaying.value = false;
  console.error('视频加载失败:', props.src);
};

// 处理进度条点击
const handleProgressBarClick = (event) => {
  const progressBar = progressBarRef.value;
  if (!progressBar || !videoRef.value) return;
  
  const rect = progressBar.getBoundingClientRect();
  const offsetX = event.clientX - rect.left;
  const percentage = offsetX / rect.width;
  const newTime = percentage * duration.value;
  
  videoRef.value.currentTime = newTime;
  currentTime.value = newTime;
};

// 开始拖动进度条
const startDrag = (event) => {
  event.preventDefault();
  isDragging.value = true;
  
  const handleDrag = (e) => {
    if (!isDragging.value || !progressBarRef.value || !videoRef.value) return;
    
    const clientX = e.clientX || (e.touches && e.touches[0].clientX);
    if (!clientX) return;
    
    const rect = progressBarRef.value.getBoundingClientRect();
    let offsetX = clientX - rect.left;
    
    // 确保在范围内
    offsetX = Math.max(0, Math.min(offsetX, rect.width));
    
    const percentage = offsetX / rect.width;
    const newTime = percentage * duration.value;
    
    currentTime.value = newTime;
    videoRef.value.currentTime = newTime;
  };
  
  const stopDrag = () => {
    isDragging.value = false;
    document.removeEventListener('mousemove', handleDrag);
    document.removeEventListener('touchmove', handleDrag);
    document.removeEventListener('mouseup', stopDrag);
    document.removeEventListener('touchend', stopDrag);
  };
  
  document.addEventListener('mousemove', handleDrag);
  document.addEventListener('touchmove', handleDrag);
  document.addEventListener('mouseup', stopDrag);
  document.addEventListener('touchend', stopDrag);
  
  // 立即执行一次，以更新初始位置
  if (event.type === 'mousedown') {
    handleDrag(event);
  } else if (event.type === 'touchstart' && event.touches.length > 0) {
    handleDrag({ clientX: event.touches[0].clientX });
  }
};

// 添加重置方法
const resetPlayer = () => {
  if (videoRef.value) {
    videoRef.value.pause();
    videoRef.value.currentTime = 0;
  }
  isPlaying.value = false;
  currentTime.value = 0;
  duration.value = 0;
  isDragging.value = false;
};

// 暴露方法给父组件
defineExpose({
  play: () => {
    if (videoRef.value) {
      videoRef.value.play();
      isPlaying.value = true;
    }
  },
  pause: () => {
    if (videoRef.value) {
      videoRef.value.pause();
      isPlaying.value = false;
    }
  },
  seekTo: (time) => {
    if (videoRef.value) {
      videoRef.value.currentTime = time;
      currentTime.value = time;
    }
  },
  resetPlayer // 暴露重置方法
});

// 修改watch部分，完善src变化时的处理逻辑
watch(() => props.src, (newSrc, oldSrc) => {
  if (newSrc !== oldSrc) {
    // 重置所有状态
    isPlaying.value = false;
    currentTime.value = 0;
    duration.value = 0;
    isDragging.value = false;
    
    // 确保视频元素存在
    if (videoRef.value) {
      // 暂停当前播放
      videoRef.value.pause();
      
      // 更新视频源 - 使用完整的方式更新
      if (videoRef.value.querySelector('source')) {
        videoRef.value.querySelector('source').src = newSrc;
      }
      
      // 重新加载视频
      videoRef.value.load();
      
      // 如果设置了自动播放，则加载完成后自动播放
      if (props.autoplay) {
        videoRef.value.onloadedmetadata = () => {
          videoRef.value.play().catch(err => {
            console.error('自动播放失败:', err);
          });
          isPlaying.value = true;
        };
      }
    }
  }
}, { immediate: true });

// 组件卸载时清理
onUnmounted(() => {
  if (videoRef.value) {
    videoRef.value.pause();
  }
});
</script>

<style scoped>
.video-player-container {
  width: 100%;
  height: 100%;
  background-color: var(--bg-color-3);
  overflow: hidden;
  position: relative;
}

.video-container {
  height: calc(100% - 48px);
  display: flex;
  justify-content: center;
  position: relative;
}

.video-element {
  width: 100%;
  display: block;
}

.controls-container {
  display: flex;
  align-items: center;
  padding: 16px 16px;
  background-color: #fff;
  color: white;
  height: 48px;
}

.play-button {
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin-right: 20px;
}

.control-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #1C1D29;
}

.time-display {
  font-size: 12px;
  min-width: 40px;
  color: var(--text-color-3);
}

.current-time {
  margin-right: 6px;
}

.total-time {
  margin-left: 6px;
}

.progress-bar-container {
  flex: 1;
  height: 2px;
  position: relative;
  cursor: pointer;
  border-radius: 3px;
  overflow: visible;
}

.progress-bar-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: var(--divide-color-grey-1);
  border-radius: 3px;
}

.progress-bar-filled {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  background-color: var(--text-color-primary);
  border-radius: 3px;
  transition: width 0.1s linear;
}

.progress-bar-handle {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 8px;
  background-color: var(--text-color-primary);
  border-radius: 50%;
  box-shadow: 0 0 4px rgba(0, 0, 0, 0.5);
  cursor: pointer;
  display: none;
}

.progress-bar-container:hover .progress-bar-handle {
  display: block;
}
</style> 